<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema } from './account.data';
import { updateAdmin, addAdmin } from '/@/api/system/admin';

const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true);
const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

const [registerForm, { setFieldsValue, resetFields, updateSchema, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: accountFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }

  updateSchema([
    {
      field: 'password',
      show: !unref(isUpdate),
      required: false,
    }
  ]);
});


async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await updateAdmin(values);
    } else {
      await addAdmin(values);
    }
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
